package com.iamdigger.server.common.util;

import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

/**
 * Pooled http client
 * Created by Sam Tsai on 2016/4/25.
 */
public class PooledHttpClient {

    private static final Logger logger = LoggerFactory.getLogger(PooledHttpClient.class);

    private static HttpClientBuilder hcb;
    private static HttpClientContext httpContext = new HttpClientContext();

    static {
        httpContext.setRequestConfig(
                RequestConfig.custom()
                        .setConnectionRequestTimeout(5000)
                        .setConnectTimeout(5000)
                        .setSocketTimeout(5000)
                        .build());

        PoolingHttpClientConnectionManager poolingConnManager = new PoolingHttpClientConnectionManager();
        poolingConnManager.setMaxTotal(20);
        poolingConnManager.setDefaultMaxPerRoute(poolingConnManager.getMaxTotal());
        poolingConnManager.closeIdleConnections(20, TimeUnit.SECONDS);

        hcb = HttpClientBuilder.create()
                .setConnectionManager(poolingConnManager)
                .disableAuthCaching()
                .disableCookieManagement()
                .setConnectionReuseStrategy(new DefaultConnectionReuseStrategy())
                .evictIdleConnections(60, TimeUnit.SECONDS);
        // Optional
        hcb.setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36");
    }

    public static String doGet(String url) {
        String responseStr = null;
        CloseableHttpClient client = hcb.build();
        try {
            CloseableHttpResponse chr = client.execute(new HttpGet(url), httpContext);
            responseStr = readInputStream(chr.getEntity().getContent());
            EntityUtils.consume(chr.getEntity());
        } catch (IOException ioe) {
            logger.error(String.format("Get [%s] error!", url), ioe);
        }
        return responseStr;
    }

    private static String readInputStream(InputStream inputStream) {
        String isString = null;
        try {
            byte[] buffer = new byte[512];
            int length;
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while ((length = inputStream.read(buffer)) > 0) {
                byteArrayOutputStream.write(buffer, 0, length);
            }
            isString = byteArrayOutputStream.toString("UTF-8");
        } catch (IOException ioe) {
            logger.error("Read response stream failed.", ioe);
        }
        return isString;
    }
}
